#include "opencv2/opencv.hpp"
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
#include <unistd.h>

#include<stdlib.h>
#define random(x) (rand()%x)

using namespace std;
using namespace std::this_thread;
using namespace std::chrono;

#include "aodopencv/jf_aod_gpu.h"

string gettime(){
    time_t t = time(0);
    char ch[64];
    strftime(ch, sizeof(ch), "%Y-%m-%d %H:%M:%S", localtime(&t)); //年-月-日 时-分-秒
    string str_time(ch);
    return str_time;
}

int main(int argc, char **argv) {

  //   cv::cuda::setDevice(FLAGS_gpuidx);
   setDevice(1);
   auto x = [&](AODOutput ao){
        // cout<<"execute callback function"<<endl;
        cv::Mat mat  = ao.mat;
        vector<AODResult> arrRes = ao.arrRes;
        for(int i = 0; i < arrRes.size(); i++){
            cv::rectangle(mat,arrRes[i].rt, cvScalar(0, 0, 255), 1, 1, 0);
            cout<<"the coordinates is "<<arrRes[i].rt<<endl;
            // string filename_ = "/picture/"+gettime()+std::to_string(random(10000))+".jpg";
        }

        // imshow("frame",mat);
        string filename = "/picture/"+gettime()+std::to_string(random(10000))+".jpg";
        imwrite(filename, mat);
        //  rectangle(frame,cv::Point(face_info[0].x0, face_info[0].y0),cv::Point(face_info[0].x1, face_info[0].y1), cvScalar(201, 102, 62), 3, 4, 0);
    };
  
  string fname = "/video/test1.mp4";
  int skipframe = 1;
  AODGpu aod;
  aod.setCallBack(x);
  // aod.setSkipFrame(skipframe);
  aod.setSensitivity(100);
  aod.setAreaThresholdMin(40);
  aod.setAreaThresholdMax(10000);
  aod.setinterval(3000);

  // cv::Rect rt = cv::Rect(200,200,600,500);
  // aod.setROI(rt);

  AODInput input;
  cv::cuda::GpuMat d_frame;
  cv::Ptr<cv::cudacodec::VideoReader> d_reader =
  cv::cudacodec::createVideoReader(fname);
  // cv::Rect rt = cv::Rect(0,50,280,220);
  // aod.setROI(rt);
  cv::TickMeter tm;
  std::vector<double> cpu_times;
  std::vector<double> gpu_times;
  int g_Pos = 0; 

  for (;;) {
    tm.reset();
    tm.start();
    if (!d_reader->nextFrame(d_frame))
      break;
    if(g_Pos % skipframe == 0){
      input.mat = d_frame;
      aod.detect(input);
    }
    // usleep(35000);
    g_Pos++;

    if(g_Pos % 500 == 0) cout<<"the current frame is "<<g_Pos<<endl;

  }
  return 0;
}
